<template>
  <div style="padding:20px">

    <!--表单组件-->
    <!--  <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"-->
    <!--             :title="crud.status.title" width="500px">-->
    <div>
      <el-button @click="save" type="primary">保存</el-button>
      <el-button @click="toCopy()" type="success">复制</el-button>
      <el-button @click="bomShow" type="success">商品BOM</el-button>
      <el-button @click="cancel" type="primary" plain>关闭</el-button>
      <!--      <el-button @click="reset()">重置</el-button>-->
    </div>
    <j-dialog
    title="商品bom"
    :visible.sync="showBom"
    style="width: 60%"
    is-mask
    >
      <el-button type="success" @click="addBomDetail">增加</el-button>
      <el-table ref="priceTble"  @row-dblclick="upIsSelected"  :data="bomForm"  border style="width: 100%">
        <el-table-column  width="300" prop="goodsCode" label="商品编码" />
        <el-table-column prop="priceSuitName"  align="center"  label="商品名称" >
          <template slot-scope="{row}">
            <z-select
              url="/api/dropDown/basGoodsListForAdd"
              :value.sync="row.goodsId"
              :showName="row.goodsName"
              class="type"
              size="999"
              labelKey="goodsName"
              valueKey="goodsId"
              @change="$event=>setBomGoods($event,row)"
            />
          </template>
        </el-table-column>
        <el-table-column   prop="model" label="规格" />
        <el-table-column  width="200" align="center" label="数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.goodsCount" />
          </template>
        </el-table-column>
        <el-table-column  width="200" align="center" label="操作">
          <template slot-scope="scope">
            <el-button @click="delBomDetail(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex jc-end">
        <el-button type="success" @click="saveBom">确认</el-button>
      </div>

    </j-dialog>
    <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="150px">
      <el-divider content-position="left">基本信息</el-divider>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="图片地址">
        <el-input v-model="form.imageUrl" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="条形码" prop="barcode">
        <el-input v-model="form.barcode" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="税号" >
        <el-input v-model="form.taxNo" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="form.code" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="商品分类" prop="goodsTypeId">
        <treeselect
            v-model="form.goodsTypeId"
            :options="typeList"
            placeholder="选择商品分类"
            style="width: 370px"
            :normalizer="normalizer"
        >
        </treeselect>
      </el-form-item>

      <el-form-item label="助记符">
        <el-input v-model="form.helpSign" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="商品品牌" prop="goodsBrandId">
        <zSelect :value.sync="form.goodsBrandId" :showName="form.goodsBrandName" :label="form.goodsBrandName" url="api/dropDown/basGoodsBrandList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="拼音">
        <el-input v-model="form.spell" style="width: 370px"/>
      </el-form-item>

      <el-form-item label="税率" prop="taxRate">
        <!--                <el-input v-model="form.taxRate" style="width: 370px"/>-->
        <zSelect :value.sync="form.taxId" :showName="form.taxName" :label="form.taxName" clearable url="api/dropDown/basTaxList"
                 style="width:  370px;" @change="o=>form.taxRate = o.rate"/>
      </el-form-item>
      <el-form-item label="手动输入税率" prop="taxRate">
        <el-input v-model="form.taxRate" style="width: 370px">
          <template slot="append">%</template>
        </el-input>
      </el-form-item>

      <el-form-item label="规格型号">
        <el-input v-model="form.model" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="商品品级">
        <el-select v-model="form.goodsLevel" class="edit-input" placeholder="请选择商品品级" style="width: 370px;">
          <el-option
              v-for="(item,index) in dict.t_bas_goods_level"
              :key="index"
              :label="item.label"
              :value="(item.value+'')"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="箱装条形码">
        <el-input v-model="form.boxBarcode" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="商品类型" prop="goodsTagId">
        <zSelect :value.sync="form.goodsTagId" :showName="form.goodsTagName" url="api/dropDown/basGoodsTagList" style="width:  370px;"/>
        <!--        <el-select v-model="form.type" class="edit-input" placeholder="请选择" style="width:  370px;">-->
        <!--          <el-option-->
        <!--              v-for="(item,index) in dict.t_bas_goods_type"-->
        <!--              :key="index"-->
        <!--              :label="item.label"-->
        <!--              :value="item.value"-->
        <!--          />-->
        <!--        </el-select>-->
      </el-form-item>
      <el-form-item label="供应商" prop="customerId">
        <zSelect :value.sync="form.customerId" :showName="form.customerName" :label="form.customerName" url="api/dropDown/basCustomerList" :params="{isContact:'1,2'}"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="所属二批">
        <zSelect :value.sync="form.scustomerId" :showName="form.scustomerName"  url="api/dropDown/basCustomerList" :params="{type:3}"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="包装类型">
        <el-select
          v-model="form.packageType" style="width: 370px;"
        >
          <el-option v-for="(item,index) in dict.t_bas_goods_package_type"
          :label="item.label"
          :key="index"
          :value="String(item.value)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="空箱商品">
        <zSelect url="/api/dropDown/basGoodsList?goodsTagName=回瓶回箱"
                 :label="name"
                 :value.sync="form.emptyBoxGoodsId"
                 :showName="form.emptyBoxGoodsName"
                 style="width:  370px;"
        >
        </zSelect>
      </el-form-item>

      <el-divider content-position="left">更多信息</el-divider>


      <el-form-item label="新商品标志期限">
        <el-input v-model="form.newGoodsExpir" style="width: 370px">
          <template slot="append">月</template>
        </el-input>
      </el-form-item>
      <!--      <el-form-item label="保质期单位">-->

      <!--      </el-form-item>-->
      <el-form-item label="保质期">
        <el-input v-model="form.expiration" style="width: 370px">
          <el-select slot="append" v-model="form.expirationUnit" class="edit-input" placeholder="请选择保质期单位"
                     style="width:  70px;">
            <el-option
                v-for="(item,index) in dict.t_bas_goods_expiration_unit"
                v-if="item.seq>0"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-input>
      </el-form-item>

      <el-form-item label="购销类型">
        <el-select v-model="form.buySaleType" class="edit-input" placeholder="请选择保购销类型" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.t_bas_goods_buy_sale_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="新商品标志截止日期">
        <el-date-picker
            v-model="form.newGoodsExpirDate" style="width: 370px"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
        </el-date-picker>
      </el-form-item>

      <!--      <el-form-item label="来源类型">-->
      <!--        <el-select v-model="form.sourceType" class="edit-input" placeholder="请选择来源类型" style="width:  370px;">-->
      <!--          <el-option-->
      <!--              v-for="(item,index) in dict.t_bas_goods_source_type"-->
      <!--              :key="index"-->
      <!--              :label="item.label"-->
      <!--              :value="item.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->


      <el-form-item label=" ">
        <el-checkbox v-model="form.isPromotion" :true-label="1" :false-label="0">允许促销</el-checkbox>
        <el-checkbox v-model="form.isBatchManage" :true-label="1" :false-label="0">批次管理</el-checkbox>
        <el-checkbox v-model="form.isBulk" :true-label="1" :false-label="0">允许散装</el-checkbox>
        <el-checkbox v-model="form.isExpirationManage" :true-label="1" :false-label="0">保质期管理</el-checkbox>
      </el-form-item>


      <el-divider content-position="left">单位管理</el-divider>
      <el-row>
      <el-form-item label="最小单位">
        <zSelect :value.sync="form.firstUnitId"  @change="$event=>setUnitLeven($event,'first',0)"  :showName="form.firstUnitName" :label="form.firstUnitName" url="api/dropDown/basUnitList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>

<!--      <el-form-item label="最小计量数">-->
<!--        <el-input v-model="form.firstUnitCount" style="width: 370px">-->
<!--          <template slot="append">{{ form.firstUnitName }}</template>-->
<!--        </el-input>-->
<!--      </el-form-item>-->
        <el-form-item >
          商品的最小单位
        </el-form-item>
      </el-row>
      <el-row>
      <el-form-item label=" 二级单位">
        <zSelect :value.sync="form.secondUnitId" @change="$event=>setUnitLeven($event,'second',1)"   :showName="form.secondUnitName" :label="form.secondUnitName" url="api/dropDown/basUnitList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
<!--      <el-form-item label="二级单位计量数">-->
<!--        <el-input v-model="form.secondUnitCount" style="width: 370px">-->
<!--          <template slot="append">{{ form.firstUnitName }}</template>-->
<!--        </el-input>-->
<!--      </el-form-item>-->
        <el-form-item >
          商品的中大单位，只存在二级换算的情况下，单位一般为箱，存在多级的时候一般为中间单位
        </el-form-item>
      </el-row>
      <el-row>
      <el-form-item label="三级单位" >
        <zSelect :value.sync="form.thirdUnitId" @change="$event=>setUnitLeven($event,'third',2)" :showName="form.thirdUnitName" :label="form.thirdUnitName" url="api/dropDown/basUnitList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
<!--      <el-form-item label="三级单位计量数">-->
<!--        <el-input v-model="form.thirdUnitCount" style="width: 370px">-->
<!--          <template slot="append">{{ form.firstUnitName }}</template>-->
<!--        </el-input>-->
<!--      </el-form-item>-->
        <el-form-item >
          商品的中大单位，只存在三级级换算的情况下，单位一般为箱，存在多级的时候一般为中间单位
        </el-form-item>
      </el-row>
      <el-row>
      <el-form-item label="四级单位">
        <zSelect :value.sync="form.fourthUnitId" @change="$event=>setUnitLeven($event,'fourth',3)" :showName="form.fourthUnitName"  :label="form.fourthUnitName"
                 url="api/dropDown/basUnitList" style="width:  370px;">
        </zSelect>
      </el-form-item>
<!--      <el-form-item label="四级单位计量数">-->
<!--        <el-input v-model="form.fourthUnitCount" style="width: 370px">-->
<!--          <template slot="append">{{ form.firstUnitName }}</template>-->
<!--        </el-input>-->
<!--      </el-form-item>-->
        <el-form-item >
          商品的最大单位，一般为箱
        </el-form-item>
      </el-row>
      <br/>
      <el-form-item label="最小销售单位">
        <zSelect :value.sync="form.minSaleUnitId" :showName="form.minSaleUnitName" :label="form.minSaleUnitName" url="api/dropDown/basUnitList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="最小退货单位">
        <zSelect :value.sync="form.minReturnUnitId" :showName="form.minReturnUnitName" :label="form.minReturnUnitName" url="api/dropDown/basUnitList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-row>
      <el-form-item label="单位换算">
        <div class="unitComputedBox" :style="{width:`${meetWith.length * 115}px`}">
          <div class="flex" v-for="item in meetWith">
            <el-input @change="changeUnit" oninput ="value=value.replace(/[^\d]/g,'')" type="number" class="count"  v-model="convertUnit[item].count" style="width: 100px" />
            <div class="name ">
              {{ convertUnit[item].name }}
            </div>
          </div>
        </div>
      </el-form-item>
      </el-row>
      <el-divider content-position="left">价格相关</el-divider>
      <el-form-item label="计价方式">
        <el-select v-model="form.priceType" class="edit-input" placeholder="请选择计价方式" style="width:  370px;">
          <el-option
              v-for="(item,index) in dict.t_bas_goods_price_type"
              :key="index"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <br/>
      <el-form-item label="采购含税单价">
        <el-input v-model="form.buyTaxPrice" :disabled="form.priceType!='SINGLE'" @input="computeBoxPrice"
                  style="width: 370px"/>
      </el-form-item>
      <el-form-item label="采购未税单价">
        <el-input v-model="form.buyNoTaxPrice" placeholder="输入税率和含税价自动计算" disabled
                  style="width: 370px"/>
      </el-form-item>


      <el-form-item label="采购含税箱价">
        <el-input v-model="form.buyTaxBoxPrice" :disabled="form.priceType!='BOX'" @input="computeSinglePrice"
                  style="width: 370px"/>
      </el-form-item>
      <el-form-item label="采购未税箱价">
        <el-input v-model="form.buyNoTaxBoxPrice" placeholder="输入税率和含税价自动计算" disabled
                  style="width: 370px"/>
      </el-form-item>


      <el-form-item label="销售含税单价">
        <el-input v-model="form.saleTaxPrice" :disabled="form.priceType!='SINGLE'" @input="computeBoxPrice"
                  style="width: 370px"/>
      </el-form-item>
      <el-form-item label="销售未税单价">
        <el-input v-model="form.saleNoTaxPrice" placeholder="输入税率和含税价自动计算" disabled
                  style="width: 370px"/>
      </el-form-item>


      <el-form-item label="销售含税箱价">
        <el-input v-model="form.saleTaxBoxPrice" :disabled="form.priceType!='BOX'" @input="computeSinglePrice"
                  style="width: 370px"/>
      </el-form-item>
      <el-form-item label="销售未税箱价">
        <el-input v-model="form.saleNoTaxBoxPrice" placeholder="输入税率和含税价自动计算" disabled
                  style="width: 370px"/>
      </el-form-item>


      <el-divider content-position="left">长宽高</el-divider>
      <el-form-item label="长">
        <el-input v-model="form.length" style="width: 370px" @input="changeVolumn">
          <template slot="append">
            m
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="宽">
        <el-input v-model="form.width" style="width: 370px" @input="changeVolumn">
          <template slot="append">
            m
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="高">
        <el-input v-model="form.height" style="width: 370px" @input="changeVolumn">
          <template slot="append">
            m
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="箱体积">
        <el-input v-model="form.volume" disabled style="width: 370px">
          <template slot="append">
            m3
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="箱重">
        <el-input v-model="form.weight" style="width: 370px">
          <template slot="append">
            kg
          </template>
        </el-input>
      </el-form-item>

      <el-divider content-position="left">仓库管理</el-divider>
      <el-form-item label="默认仓库">
        <zSelect :value.sync="form.warehouseId" :showName="form.warehouseName" :label="form.warehouseName" url="api/dropDown/basWarehouseList"
                 style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="默认库区">
        <zSelect :value.sync="form.locationId" :showName="form.locationName" :params="{warehouseId:form.warehouseId}"
                 url="api/dropDown/basLocationList"  style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="默认库位">
        <zSelect :value.sync="form.storehouseId" :showName="form.storehouseName" :label="form.storehouseName" :params="{warehouseId:form.warehouseId,locationId: form.locationId}"
                 url="api/dropDown/basStorehouseList"  style="width:  370px;">
        </zSelect>
      </el-form-item>
      <el-form-item label="最低库存">
        <el-input v-model="form.minStock" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="最高库存">
        <el-input v-model="form.maxStock" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="安全库存">
        <el-input v-model="form.safeStock" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="标箱数量">
        <el-input v-model="form.standardBoxCount" style="width: 370px"/>
      </el-form-item>
      <el-divider content-position="left">其他</el-divider>
      <el-form-item label="是否小程序销售">
        <el-select v-model="form.isAppletSale" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
              v-for="(item,index) in dict.common_yes_or_no"
              :key="index"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐商品">
        <el-select v-model="form.isRecommend" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
            v-for="(item,index) in dict.common_yes_or_no"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="每日限购数量">
        <el-input v-model="form.dailyQuotaCount" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="起订量">
        <el-input v-model="form.startSaleGoodsCount" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="是否估清">
        <el-select v-model="form.isEstimate" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
            v-for="(item,index) in dict.common_yes_or_no"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否预订">
        <el-select v-model="form.isAdvance" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
            v-for="(item,index) in dict.common_yes_or_no"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="form.seq" :min="1" label="排序" style="width: 370px;"></el-input-number>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="form.status" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
              v-for="(item,index) in dict.common_status"
              :key="index"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="蔬东坡状态">
        <!-- <el-select v-model="form.status" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
              v-for="(item,index) in dict.common_status"
              :key="index"
              :label="item.label"
              :value="item.value"
          />
        </el-select> -->
        <el-input v-model="form.shuStatus?'上架':'下架'" style="width: 370px" disabled/>
      </el-form-item>
      <el-form-item label="共同名称">
        <el-input v-model="form.commonName" type="text" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="是否积分兑换">
        <el-select v-model="form.isPointExchange" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
            v-for="(item,index) in dict.common_yes_or_no"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="积分兑换数量">
        <el-input v-model="form.exchangePointCount" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="是否拼团">
        <el-select v-model="form.isGroupBuy" class="edit-input" placeholder="请选择" style="width: 370px">
          <el-option
            v-for="(item,index) in dict.common_yes_or_no"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="拼团人数">
        <el-input v-model="form.groupBuyCount" style="width: 370px"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" style="width: 370px"/>
      </el-form-item>


      <el-divider content-position="left">历史价格</el-divider>
      <el-form-item label=" ">
        <el-table ref="priceTble"  :data="priceTbleData" border style="width: 100%">
          <el-table-column prop="name" align="center" label="价格" width="180"/>
          <el-table-column prop="taxPrice" align="center" label="含税单价" width="180"/>
          <el-table-column prop="noTaxPrice" align="center" label="未税单价" width="180"/>
          <el-table-column prop="taxBoxPrice" label="含税箱价" align="center" width="180"/>
          <el-table-column prop="noTaxBoxPrice" align="center" label="未税箱价" width="180"/>
        </el-table>
      </el-form-item>
      <!-- 勇哥说价格套可以这样做 -->
      <el-divider content-position="left">价格套价格</el-divider>
      <el-form-item label=" ">
        <el-table ref="priceTble"  @row-dblclick="upIsSelected"  :data="form.priceSuitList"  border style="width: 100%">
          <el-table-column prop="priceSuitName"  align="center" width="200" label="价格套信息" />
          <el-table-column prop="taxPrice" width="200" align="center" label="含税单价" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.taxPrice" @change="changePrice(scope.row,'taxPrice')"></el-input>
            </template>
          </el-table-column>
          <el-table-column width="200" align="center" prop="noTaxPrice" label="未税单价" />
          <el-table-column  width="200" align="center" label="含税箱价">
            <template slot-scope="scope">
                <el-input v-model="scope.row.taxBoxPrice" @change="changePrice(scope.row,'taxBoxPrice')" />
            </template>
          </el-table-column>
          <el-table-column  width="200" align="center" prop="noTaxBoxPrice" label="未税箱价" />
        </el-table>
      </el-form-item>
      <el-divider content-position="left">图片信息</el-divider>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jpg, .png"
        :action="upload.url"
        :headers="upload.headers"
        :file-list="upload.fileList"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <template>
        <el-carousel :interval="4000" type="card" height="750px">
          <el-carousel-item v-for="item in upload.imgList" :key="item">
            <div class="demo-image__preview">
              <el-image
                width="800px"
                heigth="600px"
                fit="fill"
                :src="item.path"
                >
              </el-image>
              <div class="el-icon-close jIcon" style="position: absolute" @click="delImage(index)">删除</div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </template>
      <div style="height: 100px"></div>
    </el-form>

    <!--  </el-dialog>-->
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import {getTypeList} from "@/api/erp/basGoodsType";
import crudBasGoods from '@/api/erp/basGoods'
import { getToken } from "@/utils/auth";
import JDialog from '../../../../components/jDialog/jDialog.vue'


const defaultForm = {
  id: null,
  code: null,
  name: null,
  dailyQuotaCount:0,
  isAdvance:'0',
  type: null,
  sourceType: null,
  helpSign: null,
  spell: null,
  model: null,
  barcode: null,
  boxBarcode: null,
  firstUnitId: null,
  firstUnitCode: null,
  firstUnitName: null,
  firstUnitCount: null,
  secondUnitId: null,
  secondUnitCode: null,
  secondUnitName: null,
  secondUnitCount: null,
  thirdUnitId: null,
  thirdUnitCode: null,
  thirdUnitName: null,
  thirdUnitCount: null,
  fourthUnitId: null,
  fourthUnitCode: null,
  fourthUnitName: null,
  fourthUnitCount: null,
  minSaleUnitId: null,
  minSaleUnitCode: null,
  minSaleUnitName: null,
  minSaleUnitCount: null,
  minReturnUnitId: null,
  minReturnUnitCode: null,
  minReturnUnitName: null,
  minReturnUnitCount: null,
  goodsBrandId: null,
  goodsBrandCode: null,
  goodsBrandName: null,
  taxRate: null,
  goodsTypeId: null,
  goodsTypeCode: null,
  goodsTypeName: null,
  goodsTagId: null,
  goodsTagCode: null,
  goodsTagName: null,
  goodsLevel: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  fCustomerId: null,
  fCustomerCode: null,
  fCustomerName: null,
  isBatchManage: null,
  isContact: null,
  isExpirationManage: null,
  isBulk: null,
  isPromotion: null,
  expiration: null,
  expirationUnit: null,
  newGoodsExpir: null,
  newGoodsExpirDate: null,
  buySaleType: null,
  priceType: null,
  buyTaxPrice: null,
  buyNoTaxPrice: null,
  buyTaxBoxPrice: null,
  buyNoTaxBoxPrice: null,
  saleTaxPrice: null,
  saleNoTaxPrice: null,
  saleTaxBoxPrice: null,
  saleNoTaxBoxPrice: null,
  latestBuyTaxPrice: null,
  latestBuyNoTaxPrice: null,
  latestBuyTaxBoxPrice: null,
  latestBuyNoTaxBoxPrice: null,
  latestSaleTaxPrice: null,
  latestSaleNoTaxPrice: null,
  latestSaleTaxBoxPrice: null,
  latestSaleNoTaxBoxPrice: null,
  latestPromotionTaxPrice: null,
  latestPromotionNoTaxPrice: null,
  latestPromotionTaxBoxPrice: null,
  latestPromotionNoTaxBoxPrice: null,
  latestCustomerId: null,
  latestCustomerCode: null,
  latestCustomerName: null,
  length: null,
  width: null,
  height: null,
  volume: null,
  weight: null,
  imageUrl: null,
  minStock: null,
  maxStock: null,
  safeStock: null,
  warehouseId: null,
  warehouseCode: null,
  warehouseName: null,
  storehouseId: null,
  storehouseCode: null,
  storehouseName: null,
  standardBoxCount: null,
  isAppletSale: null,
  seq: null,
  status: null,
  remark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  priceSuitList: [],
  emptyBoxGoodsId: null,
  scustomerId:null,
  scustomerName: null,
  startSaleGoodsCount: 0
}
export default {
  name: 'basGoodsDetail',
  components: { JDialog, Treeselect},
  dicts: ['t_bas_goods_type', 'common_status', 't_bas_goods_buy_sale_type', 'common_yes_or_no',
    't_bas_goods_price_type', 't_bas_goods_expiration_unit', 't_bas_goods_level', 't_bas_goods_source_type',
    't_bas_goods_package_type'],
  data() {
    return {
      rules: {
        goodsTagId:[
          {required: true, message: '类型不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '编码不能为空', trigger: 'blur'}
        ],
        customerId: [
          {required: true, message: '供应商不能为空', trigger: 'blur'}
        ],
        scustomerId: [
          {required: true, message: '所属二批不能为空', trigger: 'blur'}
        ],
      },
      showBom:false,
      brandList: [],
      typeList: [],
      unitList: [],
      goodsTagList: [],
      form: defaultForm,
      id: 0,
      saveFlag: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: '',
        // 上传的文件列表
        fileList: [],

        imgList:[]
      },
      convertUnit:{},
      unitTypeList:['first','second','third','fourth'],
      meetWith:[],
      bomForm:[]
    }
  },
  watch: {
    "form.imageUrl"(){
      this.upload.imgList = JSON.parse(this.form.imageUrl)
    }
  },
  computed: {
    priceTbleData: function () {//价格表格数据
      return [
        {
          name: '最近采购',
          taxPrice: this.form.latestBuyTaxPrice,
          noTaxPrice: this.form.latestBuyNoTaxPrice,
          taxBoxPrice: this.form.latestBuyTaxBoxPrice,
          noTaxBoxPrice: this.form.latestBuyNoTaxBoxPrice,
        },
        {
          name: '最近销售',
          taxPrice: this.form.latestSaleTaxPrice,
          noTaxPrice: this.form.latestSaleNoTaxPrice,
          taxBoxPrice: this.form.latestSaleTaxBoxPrice,
          noTaxBoxPrice: this.form.latestSaleNoTaxBoxPrice,
        },
        {
          name: '最近促销',
          taxPrice: this.form.latestPromotionTaxPrice,
          noTaxPrice: this.form.latestPromotionNoTaxPrice,
          taxBoxPrice: this.form.latestPromotionTaxBoxPrice,
          noTaxBoxPrice: this.form.latestPromotionNoTaxBoxPrice,
        }
      ]

    },

  },
  activated() {
    let id = this.$route.query.id
    this.upload.url = window.location.href.split('/').slice(0,3).join('/')+'/api/common/uploadImage'
    if (id != null) {
      //查询商品详情
      this.id = id
      //从cookie中获取数据
      // let _form = Cookies.get("goodsForm_" + id)
      try {
        let _form = JSON.parse(sessionStorage.getItem("goodsForm_" + id));
        if (_form != null) {
          // _form.priceSuitList.forEach(item=>item.isSelected = false)
          this.form = _form
          this.setUnit()
        } else {
          if (id != 0) {
            this.getOneById(id)
          }else{
            sessionStorage.removeItem("goodsForm_" + this.id);
              this.form = JSON.parse(JSON.stringify(defaultForm))
              this.setUnit()
          }
        }
      } catch (e) {
        //如果没有数据，就进行联网查询
        if (id != 0) {
          this.getOneById(id)
        }
      }
    } else {
    }
    // this.getBrandList()
    this.getTypeList()
    // this.getUnitList()
    // this.getGoodsTagList()
    this.upload.imgList = JSON.parse(this.form.imageUrl)
  },
  directive(id, definition) {
    if (!this.saveFlag) {
      sessionStorage.setItem("goodsForm_" + this.id, JSON.stringify(this.form));
    }
  },
  created() {
    let id = this.$route.query.id
     this.upload.url = window.location.href.split('/').slice(0,3).join('/')+'/api/common/uploadImage'
    if (id != null) {
      //查询商品详情
      this.id = id
      //从cookie中获取数据
      // let _form = Cookies.get("goodsForm_" + id)
      try {
        let _form = JSON.parse(sessionStorage.getItem("goodsForm_" + id));
        if (_form != null) {
          // _form.priceSuitList.forEach(item=>item.isSelected = false)
          this.form = _form
        } else {
          if (id != 0) {
            this.getOneById(id)
          }
        }
      } catch (e) {
        //如果没有数据，就进行联网查询
        if (id != 0) {
          this.getOneById(id)
        }
      }
    } else {
    }
    // this.getBrandList()
    this.getTypeList()
    // this.getUnitList()
    // this.getGoodsTagList()
    this.upload.imgList = JSON.parse(this.form.imageUrl)
  },
  destroyed() {
    // Cookies.set("goodsForm_" + this.id, JSON.stringify(this.form))
    if (!this.saveFlag) {
      sessionStorage.setItem("goodsForm_" + this.id, JSON.stringify(this.form));
    }
  },
  methods: {
    bomShow(){
      this.bomForm = JSON.parse(JSON.stringify(this.form.bomInfoList)) || []
      this.showBom = true
    },
    setBomGoods(e,row){
      row.goodsCode = e.goodsCode
      row.goodsName = e.goodsName
      row.model = e.model
      row.goodsCount = 1
    },
    delBomDetail(index){
      this.bomForm.splice(index,1)
    },
    addBomDetail(){
      this.bomForm.push({
        goodsId:null,
        goodsCode:null,
        goodsName:null,
        goodsCount:null,
      })
    },
    delImage(index) {
      this.$confirm('此操作将永久删除该图片, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.upload.imgList.splice(index, 1)
      }).catch(() => {
      })
    },
    changeUnit(){
      this.meetWith.reduce((pre,cur)=>{
        this.form[`${cur}UnitCount`] = pre
        return pre*Number(this.convertUnit[cur].count)
      },1)
      console.log(this.form)
    },
    setUnit(){
      //获取有数据的计量单位
      this.meetWith = this.unitTypeList.filter((item,nIndex)=>this.form[`${item}UnitId`])
      //不允许为小数
      for (let i = 0;i<this.meetWith.length;i++){
        if (i<this.meetWith.length-1){
          this.$set(
            this.convertUnit,
            this.meetWith[i], {
            type:i,
            name:this.form[`${this.meetWith[i]}UnitName`],
            count:(this.form[`${this.meetWith[i+1]}UnitCount`] / this.form[`${this.meetWith[i]}UnitCount`]) >> 0,
            seq:this.unitTypeList.indexOf(this.meetWith[i])
          })
        }else{
          this.$set(
            this.convertUnit,
            this.meetWith[i], {
            type:i,
            name:this.form[`${this.meetWith[i]}UnitName`],
            count:1,
            seq:this.unitTypeList.indexOf(this.meetWith[i])
          })
        }
      }
    },

    changePrice(row,type){
      if (type === 'taxBoxPrice'){
        this.$set(row,'taxPrice',row.taxBoxPrice/this.getUnitCont())
        this.$set(row,'noTaxPrice',row.taxPrice*(1-(this.form.taxRate/100)))
        this.$set(row,'noTaxBoxPrice',row.taxBoxPrice*(1-(this.form.taxRate/100)))
      }else if(type === 'taxPrice'){
        this.$set(row,'taxBoxPrice',row.taxPrice*this.getUnitCont())
        this.$set(row,'noTaxPrice',row.taxPrice*(1-(this.form.taxRate/100)))
        this.$set(row,'noTaxBoxPrice',row.taxBoxPrice*(1-(this.form.taxRate/100)))
      }
    },
    getUnitCont(){
      return this.form.fourthUnitCount || this.form.thirdUnitCount || this.form.secondUnitCount || 1
    },
    handleAdd() {
      this.upload.fileList = [];
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      if (this.upload.imgList === null){this.upload.imgList = []}
      this.upload.imgList.push({ path:response.data.path,realName:response.data.realName,id:response.data.id })
      this.form.imageUrl = JSON.stringify(this.upload.imgList)
      this.save()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    upIsSelected(row){
      row.isSelected = !row.isSelected
    },
    changeVolumn() {
      this.form.volume = this.form.length * this.form.width * this.form.height
    },
    setUnitLeven(e,type,leven){
      if (e){
        this.$set(
          this.convertUnit,
          type, {
          type,
          name:e.name,
          count:1,
          seq:leven
        })
      }else{
        this.$delete(this.convertUnit,type)
      }
      this.meetWith = Object.keys(this.convertUnit)
      this.meetWith.sort((a,b)=>this.convertUnit[a].seq-this.convertUnit[b].seq)
      this.changeUnit()
    },
    saveBom(){
      this.form.bomInfoList = this.bomForm
      this.showBom = false
    },
    getOneById(id) {
      crudBasGoods.get({id: id}).then(res => {
        if(res.data.content.length>0){
          // res.data.content[0].priceSuitList.forEach(item=>item.isSelected = false)
          this.form = res.data.content[0]
          this.setUnit()
        }
      })
    },
    save() {
      if (this.upload.imgList){
        this.form.imageUrl = JSON.stringify(this.upload.imgList)
      }

      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.meetWith.reduce((pre,cur)=>{
            this.form[`${cur}UnitCount`] = pre
            return pre*Number(this.convertUnit[cur].count)
          },1)

          crudBasGoods.add(this.form).then(res => {
            //  this.form = JSON.parse(JSON.stringify(defaultForm))
            if (res.status == 200) {
              this.$message.success(res.msg)
              //删除cookie
              // Cookies.remove("goodsForm_" + this.id)
              sessionStorage.removeItem("goodsForm_" + this.id);
              this.form = JSON.parse(JSON.stringify(defaultForm))
              this.setUnit()
              this.cancel()
            } else {
              // this.$message.error((res.))
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    cancel() {
      this.$store.dispatch('tagsView/delView', {
        path: '/bas/goods/basGoodsDetail/' + this.id,
      }).then(({visitedViews}) => {
        this.saveFlag = true
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView)
        } else {
          // now the default is to redirect to the home page if there is no tags-view,
          // you can adjust it according to your needs.
          // if (view.name === 'Dashboard') {
          //   // to reload home page
          //   this.$router.replace({path: '/redirect' + view.fullPath})
          // } else {
          //   this.$router.push('/')
          // }
        }
      })
    },

    toCopy(event) {

      let _data = JSON.parse(JSON.stringify(this.form))
      //删除id
      _data.id=null
      _data.name = '复制—'+this.form.name
      _data.code = this.form.code + "1"
      _data.priceSuitList = null

      _data.latestBuyTaxPrice = null
       _data.latestBuyNoTaxPrice = null
       _data.latestBuyTaxBoxPrice = null
       _data.latestBuyNoTaxBoxPrice = null
       _data.latestSaleTaxPrice = null
       _data.latestSaleNoTaxPrice = null
       _data.latestSaleTaxBoxPrice = null
       _data.latestSaleNoTaxBoxPrice = null
       _data.latestPromotionTaxPrice = null
       _data.latestPromotionNoTaxPrice = null
       _data.latestPromotionTaxBoxPrice = null
       _data.latestPromotionNoTaxBoxPrice = null
      _data.costTaxPrice = 0
      _data.costNoTaxPrice = 0
      _data.buyTaxBoxPrice = 0
      _data.buyNoTaxBoxPrice = 0
      _data.saleTaxPrice = 0
      _data.saleNoTaxPrice = 0
      _data.saleTaxBoxPrice = 0
      _data.saleNoTaxBoxPrice = 0
      _data.latestBuyTaxPrice = 0
      _data.latestBuyNoTaxPrice = 0
      _data.latestBuyTaxBoxPrice = 0
      _data.latestBuyNoTaxBoxPrice = 0
      _data.latestSaleTaxPrice = 0
      _data.latestSaleNoTaxPrice = 0
      _data.latestSaleTaxBoxPrice = 0
      _data.latestSaleNoTaxBoxPrice = 0
      _data.latestPromotionTaxPrice = 0
      _data.latestPromotionNoTaxPrice = 0
      _data.latestPromotionTaxBoxPrice = 0
      _data.latestPromotionNoTaxBoxPrice = 0
      _data.buyNoTaxPrice = 0
      _data.buyTaxPrice = 0
      _data.imageUrl = null
      _data.volume = 0
      _data.width = 0
      _data.height = 0
      _data.weight = 0

      sessionStorage.setItem("goodsForm_"+_data.code, JSON.stringify(_data));
      //打开一个新增界面
      this.$router.push({
        path: '/bas/goods/basGoodsDetail/' + _data.code,
        query: {id: _data.code},
        title: '新增商品档案'
      })

    },
    reset(){
        // this.form = JSON.parse(JSON.stringify(defaultForm))
    },
    paste() {

    },
    // getGoodsTagList() {
    //   getGoodsTagList({page: 0, size: 999}).then(res => {
    //     this.goodsTagList = res.data.content
    //   })
    // },
    // getUnitList() {
    //   getUnitList({page: 0, size: 999}).then(res => {
    //     this.unitList = res.data.content
    //   })
    // },
    // getBrandList() {
    //   getBrandList({page: 0, size: 999}).then(res => {
    //     this.brandList = res.data.content
    //   })
    // },
    getTypeList() {
      getTypeList({page: 0, size: 999}).then(res => {
        this.typeList = res
      })
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    setBrand(id) {
      //id为品牌id
      let obj = this.brandList.find(o => {
        return o.id == id
      })
      this.form.taxRate = obj.taxRate
    },
    //默认保留6位
    formatNum: function (num, n = 6) {
      n = n ? parseInt(n) : 0;
      if (n <= 0) {
        return Math.round(num);
      }
      num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
      num = Number(num).toFixed(n); //补足位数
      return num;
    },
    computeSinglePrice() {
      //根据箱价计算单价
      let boxCount = 0
      if (this.form.fourthUnitId) {
        boxCount = this.form.fourthUnitCount
      } else if (this.form.thirdUnitId) {
        boxCount = this.form.thirdUnitCount
      }else{
        boxCount = this.form.secondUnitCount
      }

      this.form.saleTaxPrice = this.formatNum(this.form.saleTaxBoxPrice / boxCount)
      this.form.buyTaxPrice = this.formatNum(this.form.buyTaxBoxPrice / boxCount)

      this.computedNoTaxPrice()
    },
    computeBoxPrice() {
      //根据单价计算箱价
      //一级单位就是只，最高级单位就是箱
      //取最高级单位
      let boxCount = 0
      if (this.form.fourthUnitId) {
        boxCount = this.form.fourthUnitCount
      } else if (this.form.thirdUnitId) {
        boxCount = this.form.thirdUnitCount
      }else{
        boxCount = this.form.secondUnitCount
      }

      this.form.saleTaxBoxPrice = this.formatNum(this.form.saleTaxPrice * boxCount)
      this.form.buyTaxBoxPrice = this.formatNum(this.form.buyTaxPrice * boxCount)
      this.computedNoTaxPrice()
    },
    computedNoTaxPrice() {
      //计算4个未税价格
      this.form.saleNoTaxBoxPrice = this.formatNum(this.form.saleTaxBoxPrice / (1 + this.form.taxRate / 100))
      this.form.saleNoTaxPrice = this.formatNum(this.form.saleTaxPrice / (1 + this.form.taxRate / 100))
      this.form.buyNoTaxBoxPrice = this.formatNum(this.form.buyTaxBoxPrice / (1 + this.form.taxRate / 100))
      this.form.buyNoTaxPrice = this.formatNum(this.form.buyTaxPrice / (1 + this.form.taxRate / 100))
    },
  }
}
</script>

<style scoped>
.unitComputedBox{
  display: flex;
  width: 4 5px;
  flex-direction: row-reverse;
  height: 100%;
  .name{
    font-weight: bold;
    color: #606266;
    height: 100%;
    font-size: 14px;
    display: flex;
    align-items: center;
  }

}
</style>
